<template>
  <el-dialog
    v-model="visible"
    :title="orders.length > 1 ? '批量下发' : '订单下发'"
    width="1000px"
    align-center
    :close-on-click-modal="false"
    destroy-on-close
    draggable
    @close="handleClose"
  >
    <!-- 顶部信息条 -->
    <el-alert
      type="info"
      :closable="false"
      class="mb-3 nice-alert"
      :title="`已选 ${orders.length} 笔订单｜合计 ${formatCurrency(totalAmount)}`"
    />

    <!-- 订单列表 -->
    <template v-if="orders.length">
      <el-table
        :data="orders"
        style="width: 100%"
        border
        row-key="orderId"
        :height="orders.length > 2 ? 260 : 'auto'"
        :header-cell-style="headerCellStyle"
        :row-class-name="zebraRow"
        :tree-props="{ children: 'childrens', checkStrictly: true }"
        class="rounded-table"
      >
        <el-table-column type="index" width="60" label="#" />
        <el-table-column prop="orderNo" label="订单号" width="140" show-overflow-tooltip />
        <!-- 订单信息 -->
        <el-table-column label="订单信息">
          <template #default="{ row }">
            <!-- 平台订单 -->
            <RowSlots v-if="row.orderType == 1" slotName="orderSlot" :row="row" />
            <!-- 复购订单 -->
            <RowSlots v-else slotName="repeatOrderSlot" :row="row" />
          </template>
        </el-table-column>
        <el-table-column prop="customer" label="客户信息" width="220">
          <template #default="{ row }">
            <!-- 平台订单 -->
            <RowSlots v-if="row.orderType == 1" slotName="logisticsSlot" :row="row" />
            <!-- 复购订单 -->
            <RowSlots v-else slotName="repeatLogisticsSlot" :row="row" />
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="其他信息" width="200">
          <template #default="{ row }">
            <!-- 平台订单 -->
            <RowSlots v-if="row.orderType == 1" slotName="orderTimerSlot" :row="row" />
            <!-- 复购订单 -->
            <RowSlots
              v-if="row.orderType == 2"
              slotName="repeatDosageSlot"
              :goodsTypes="goodsTypes"
              :row="row"
            />
          </template>
        </el-table-column>

        <template #empty>
          <div class="empty-box">
            <el-icon><document-remove /></el-icon>
            <div>暂无订单数据</div>
          </div>
        </template>
      </el-table>
    </template>

    <!-- 表单 -->
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" class="mt-16 form-grid">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="下发对象" prop="issuer">
            <el-select v-model="form.issuer" placeholder="请选择下发人员" filterable>
              <el-option
                v-for="user in users"
                :key="user.userId"
                :label="`${user.nickName}(${user.phonenumber})`"
                :value="user.userId"
              >
                <div class="option-item">
                  <el-avatar :size="22">{{ user.nickName?.slice(0, 1) || '' }}</el-avatar>
                  <span>{{ `${user.nickName}(${user.phonenumber})` }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="下发备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入备注"
          :rows="3"
          maxlength="200"
          show-word-limit
        />
        <div class="remark-suggestions">
          <span class="tip">快捷备注：</span>
          <el-space>
            <el-tag
              v-for="tag in commonRemarks"
              :key="tag"
              size="small"
              class="cursor"
              @click="appendRemark(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-link type="danger" :underline="false" @click="clearRemark"> 清空 </el-link>
          </el-space>
        </div>
      </el-form-item>
    </el-form>

    <!-- 页脚 -->
    <template #footer>
      <div class="footer-bar">
        <div class="sum">
          <el-tag type="info" effect="plain">笔数：{{ orders.length }}</el-tag>
          <el-tag type="success" effect="plain" class="ml-2">
            实付金额合计：{{ formatCurrency(totalAmount) }}
          </el-tag>
        </div>
        <div class="actions">
          <el-space>
            <el-button @click="handleClose">取消</el-button>
            <el-button
              type="success"
              :loading="submitting"
              :disabled="!form.issuer || !orders.length"
              @click="handleConfirm()"
            >
              下发业务员
            </el-button>
          </el-space>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { DocumentRemove } from '@element-plus/icons-vue';
import { assignOrderToSalesman } from '../../api/platformOrders/orders/list';
import { applyRemarks } from '../../utils/order';
import { cloneDeep } from 'lodash';
import useUserStore from '../../store/modules/user';

const userApp = useUserStore();

// 改成props接收
defineProps({
  // 物流公司
  logisticsCompany: {
    type: Array,
    default: () => []
  },
  // 下发人
  users: {
    type: Array,
    default: () => []
  },
  // 物流类型
  logisticsTypeOptions: {
    type: Array,
    default: () => []
  },
  sysSelfFulfillmentOgistics: {
    type: Array,
    default: () => []
  }
});

const visible = ref(false);
const submitting = ref(false);
const orders = ref([]);

// 判断是 平台订单 还是 复购订单
// 1系统 2复购
const isPlatformOrder = computed(() => {
  return orders.value[0].orderType;
});

const emit = defineEmits(['ok']);

const form = reactive({
  issuer: '',
  remark: '',
  // 物流类型 1 自主发货 2 系统物流
  shippingType: '1',
  logisticsPlatformCode: ''
});

const rules = {
  issuer: [{ required: true, message: '请选择下发人', trigger: 'change' }],
  remark: [{ min: 0, max: 200, message: '备注不超过 200 字', trigger: 'blur' }],
  logisticsPlatformCode: [{ required: true, message: '请选择物流公司', trigger: 'change' }]
};

const formRef = ref();

const totalAmount = computed(() =>
  orders.value.reduce((sum, r) => sum + Number(r.actualPrice || 0), 0)
);

function formatCurrency(num) {
  try {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY'
    }).format(num || 0);
  } catch {
    return `¥${(num || 0).toFixed(2)}`;
  }
}

/** 表格样式 */
function headerCellStyle() {
  return { background: 'var(--el-fill-color-light)', fontWeight: 600 };
}
function zebraRow({ rowIndex }) {
  return rowIndex % 2 === 1 ? 'zebra' : '';
}

/** 备注快捷标签 */
const commonRemarks = ['优先处理', '需二次确认', '资料已齐全', '客户已沟通', '紧急'];
function appendRemark(t) {
  if (!form.remark) form.remark = t;
  else if (!form.remark.includes(t))
    form.remark += (form.remark.endsWith('，') || form.remark.endsWith(',') ? '' : '，') + t;
}
function clearRemark() {
  form.remark = '';
}

/** 打开弹窗：父组件调用 */
function show(orderList) {
  const deepList = cloneDeep(Array.isArray(orderList) ? orderList : []);
  applyRemarks(deepList, userApp.printStr);
  orders.value = deepList;
  form.issuer = '';
  form.remark = '';
  visible.value = true;
  nextTick(() => formRef.value?.clearValidate());
}

function handleClose() {
  visible.value = false;
  submitting.value = false;
}

function handleConfirm() {
  if (!orders.value.length) {
    ElMessage.warning('请先选择订单');
    return;
  }
  formRef.value?.validate((valid) => {
    if (!valid) return;
    submitting.value = true;
    const ids = orders.value.map((r) => r.orderId);
    const salesmanId = form.issuer;

    const payload = {
      salesmanId,
      remark: form.remark?.trim(),
      ids
    };

    // 下发订单至业务员
    assignOrderToSalesman(payload)
      .then((res) => {
        submitting.value = false;
        if (res.code === 200) {
          ElMessage.success('下发成功');
          emit('ok');
          handleClose();
        }
      })
      .catch(() => {
        submitting.value = false;
      });
  });
}

defineExpose({ show });
</script>

<style lang="scss" scoped>
.cursor {
  cursor: pointer;
}

.nice-alert {
  border-radius: 12px;

  :deep(.el-alert__title) {
    font-weight: 600;
  }
}

.rounded-table :deep(.el-table__inner-wrapper) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.zebra) td {
  background-color: var(--el-fill-color-lighter);
}

.empty-box {
  padding: 24px 0;
  color: var(--el-text-color-secondary);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 6px 16px;
}

.option-item {
  display: flex;
  align-items: center;

  & > span {
    margin-left: 10px;
  }
}

.remark-suggestions {
  margin-top: 6px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  .tip {
    color: var(--el-text-color-secondary);
    margin-right: 8px;
    font-size: 12px;
  }
}

.ml-2 {
  margin-left: 10px;
}

.footer-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;

  .sum {
    display: flex;
    align-items: center;
  }

  .actions {
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

/* 深色模式的小优化 */
:root.dark {
  .nice-alert {
    border: 1px solid var(--el-border-color);
  }
}

// 单条卡片
.single-order-card {
  border: 1px solid #ebeef5;
  border-radius: 12px;
  background-color: #ffffff;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin: 16px 0;
  transition: all 0.3s ease;
}

.single-order-card:hover {
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  align-items: center;
  padding: 18px 24px;
  background: linear-gradient(135deg, #1a73e8, #4285f4);
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.card-header .el-icon {
  margin-right: 10px;
  font-size: 20px;
}

.card-header .title {
  margin-right: auto;
}

.order-status-tag {
  font-weight: bold;
}

.card-body {
  padding: 24px;
  line-height: 1.8;
  color: #333;
}

.info-row {
  display: flex;
  margin-bottom: 16px;
  font-size: 15px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.label {
  width: 100px;
  font-weight: 600;
  color: #1a73e8;
  display: flex;
  align-items: flex-start;
}

.value {
  flex: 1;
  color: #555;
}

.value .address {
  color: #777;
  font-size: 14px;
  margin: 4px 0;
}

.actual-price {
  color: #e91e63 !important;
  font-size: 17px;
}

.card-footer {
  padding: 16px 24px;
  text-align: right;
  border-top: 1px dashed #ebeef5;
  background-color: #fafafa;
  border-radius: 0 0 12px 12px;
}

.card-footer .el-button {
  min-width: 100px;
}
</style>
